package com.ruoyi.project.ledger.controller;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.security.service.PermissionService;
import com.ruoyi.project.ledger.domain.LedgerBusinessAccount;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysUser;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.ledger.domain.LedgerBusinessWorker;
import com.ruoyi.project.ledger.service.ILedgerBusinessWorkerService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 经营户人员Controller
 *
 * @author gwc
 * @date 2020-05-08
 */
@RestController
@RequestMapping("/ledger/businessworker")
public class LedgerBusinessWorkerController extends BaseController
{
    @Autowired
    private ILedgerBusinessWorkerService ledgerBusinessWorkerService;
    @Autowired
    private PermissionService permissionService;

    /**
     * 查询经营户人员列表
     */
//    @PreAuthorize("@ss.hasPermi('ledger:businessworker:list')")
    @GetMapping("/list")
    public TableDataInfo list(LedgerBusinessWorker ledgerBusinessWorker)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 场站id
        Long stationId = user.getStationId();
        if(stationId != null){
            ledgerBusinessWorker.setStationId(stationId);
        }
        // 管辖区域
        List<String> areaList = user.getAreaList();
        String areas = String.join(",", areaList);
        String managementCharacters = user.getManagementCharacters();
        ledgerBusinessWorker.setAreas(areas);
        ledgerBusinessWorker.setManagementCharacters(managementCharacters);
        startPage();
        List<LedgerBusinessWorker> list = ledgerBusinessWorkerService.selectLedgerBusinessWorkerList(ledgerBusinessWorker);
        return getDataTable(list);
    }

    /**
     * 导出经营户人员列表
     */
//    @PreAuthorize("@ss.hasPermi('ledger:businessworker:export')")
    @Log(title = "经营户人员", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(LedgerBusinessWorker ledgerBusinessWorker)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 场站id
        Long stationId = user.getStationId();
        if(stationId != null){
            ledgerBusinessWorker.setStationId(stationId);
        }
        // 管辖区域
        List<String> areaList = user.getAreaList();
        String areas = String.join(",", areaList);
        String managementCharacters = user.getManagementCharacters();
        ledgerBusinessWorker.setAreas(areas);
        ledgerBusinessWorker.setManagementCharacters(managementCharacters);
        List<LedgerBusinessWorker> list = ledgerBusinessWorkerService.selectLedgerBusinessWorkerList(ledgerBusinessWorker);
        int i=0;
        for (LedgerBusinessWorker worker : list){
            worker.setId(Long.valueOf(++i));
        }
        ExcelUtil<LedgerBusinessWorker> util = new ExcelUtil<LedgerBusinessWorker>(LedgerBusinessWorker.class);
        return util.exportExcel(list, "经营户人员");
    }

    /**
     * 导入经营户人员
     * @param file
     * @param updateSupport
     * @return
     * @throws Exception
     */
    @Log(title = "经营户人员", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('ledger:businessworker:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        Long stationId = null;
        // 判断是否是场站角色
        if(!permissionService.hasRole("admin") && (permissionService.hasRole("station") || permissionService.hasRole("hs_station"))){
        } else {
            return AjaxResult.error("当前角色无导入权限");
        }
        ExcelUtil<LedgerBusinessWorker> util = new ExcelUtil<>(LedgerBusinessWorker.class);
        List<LedgerBusinessWorker> businessWorkerList = util.importExcel(file.getInputStream());
        String message = ledgerBusinessWorkerService.importAccount(businessWorkerList, updateSupport);
        return AjaxResult.success(message);
    }

    /**
     * 获取经营户人员详细信息
     */
//    @PreAuthorize("@ss.hasPermi('ledger:businessworker:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(ledgerBusinessWorkerService.selectLedgerBusinessWorkerById(id));
    }

    /**
     * 新增经营户人员
     */
    @PreAuthorize("@ss.hasPermi('ledger:businessworker:add')")
    @Log(title = "经营户人员", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LedgerBusinessWorker ledgerBusinessWorker)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 判断是否是场站角色
        if(!permissionService.hasRole("admin") && (permissionService.hasRole("station") || permissionService.hasRole("hs_station"))){
            ledgerBusinessWorker.setCreateId(user.getUserId().toString());
        }else{
            return AjaxResult.error("当前角色无新增权限");
        }
        if (UserConstants.NOT_UNIQUE.equals(ledgerBusinessWorkerService.checkWorkerNameUnique(ledgerBusinessWorker)))
        {
            return AjaxResult.error("新增经营户人员失败，姓名已存在");
        }
        return toAjax(ledgerBusinessWorkerService.insertLedgerBusinessWorker(ledgerBusinessWorker));
    }

    /**
     * 修改经营户人员
     */
    @PreAuthorize("@ss.hasPermi('ledger:businessworker:edit')")
    @Log(title = "经营户人员", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody LedgerBusinessWorker ledgerBusinessWorker)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 判断是否是场站角色
        if(!permissionService.hasRole("admin") && (permissionService.hasRole("station") || permissionService.hasRole("hs_station"))){
            ledgerBusinessWorker.setUpdateId(user.getUserId().toString());
        }else{
            return AjaxResult.error("当前角色无修改权限");
        }
        if (UserConstants.NOT_UNIQUE.equals(ledgerBusinessWorkerService.checkWorkerNameUnique(ledgerBusinessWorker)))
        {
            return AjaxResult.error("修改经营户人员失败，姓名已存在");
        }
        return toAjax(ledgerBusinessWorkerService.updateLedgerBusinessWorker(ledgerBusinessWorker));
    }

    /**
     * 删除经营户人员
     */
    @PreAuthorize("@ss.hasPermi('ledger:businessworker:remove')")
    @Log(title = "经营户人员", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(ledgerBusinessWorkerService.deleteLedgerBusinessWorkerByIds(ids));
    }

}
